package cn.com.startai.smartadh5.main.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.SPUtils;
import com.orhanobut.logger.Logger;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.startai.smartadh5.R;
import cn.com.startai.smartadh5.db.db.entity.PlayInfo;
import cn.com.startai.smartadh5.db.db.manager.PlayInfoHelper;
import cn.com.startai.smartadh5.db.sp.SPManager;
import cn.com.startai.smartadh5.extension.utils.LogUtil;
import cn.com.startai.smartadh5.extension.utils.NmcUtils;
import cn.com.startai.smartadh5.main.view.SimpleVideoView;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayStateChangeBean;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayModeChangedEvent;

import static com.shuyu.gsyvideoplayer.video.base.GSYVideoView.CURRENT_STATE_PLAYING;

/**
 * @author 尹晓童
 * 邮箱：yinxtno1@yeah.net
 * 时间：2018/1/22
 * 作用：视频播放页面
 */

public class VideoFragment extends BaseFragment {

    private final int HANDLER_WHAT_SAVE_PROGRESS = 0x10;
    private final int HANDLER_WHAT_QUERY_PLAY_LIST = 0x11;
    public final static String IMG_TRANSITION = "IMG_TRANSITION";

    public static final String TAG = "VideoFragment";

    @BindView(R.id.video_view)
    SimpleVideoView videoView;

    private long curPlayId = -1;
    private int curProgress = 0;
    private List<PlayInfo> mPlayList = new ArrayList<>();

    private Handler mMainHandler;

    /**
     * 重新进入到当前页后，是否自动开始播放
     */
    private boolean isAutoPlay = true;
    public boolean isInit = false;

    private HandlerThread mHandlerThread;
    private Handler mHandler;



    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_video, container, false);
    }

    @Override
    public void initData() {
        initHandler();
         mMainHandler = new Handler();
        EventBus.getDefault().register(this);
    }

    private void initHandler() {
        mHandlerThread = new HandlerThread("[VideoFragment.mHandlerThread]",
                Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case HANDLER_WHAT_SAVE_PROGRESS:
                        //保存
                        int progress = 0;
                        try {
                            long id = (long) msg.obj;
                            progress = msg.arg1;
                            if (id != curPlayId) {
                                SPManager.getInstance().saveCurrentVideoPlayId(id);
                                curPlayId = id;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        SPManager.getInstance().saveCurrentVideoPlayProgress(progress);
                        break;
                    case HANDLER_WHAT_QUERY_PLAY_LIST:
                        //查询播放列表
                        List<PlayInfo> playList = PlayInfoHelper.getInstance()
                                .queryListByType(PlayInfo.TYPE_VIDEO);
                        mPlayList.clear();
                        mPlayList.addAll(playList);
                        NmcUtils.sendToNmcPlayListChanged(PlayInfo.TYPE_VIDEO, playList);
                        if (playList.isEmpty()) {
                            NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
                            return;
                        }
                        long playId = SPManager.getInstance().getCurrentVideoPlayId();
                        int playProgress = SPManager.getInstance().getCurrentVideoPlayProgress();

                        mContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int position = 0;
                                PlayInfo needPlay = null;
                                if (playId != -1) {
                                    for (int i = 0; i < playList.size(); i++) {
                                        if (playList.get(i).getId() == playId) {
                                            needPlay = playList.get(i);
                                            position = i;
                                            break;
                                        }
                                    }
                                }
                                videoView.setUp(playList, false, position, null);
                                if (needPlay != null) {
                                    LogUtil.v(TAG, " HANDLER_WHAT_QUERY_PLAY_LIST  setSeekOnStart ");
                                    videoView.setSeekOnStart((long) (playProgress * 1.0f / 100 * needPlay.getDuration()));
                                }
                                mMainHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        LogUtil.v(TAG, " HANDLER_WHAT_QUERY_PLAY_LIST  startPlayLogic ");
                                        videoView.startPlayLogic();
                                    }
                                }, 500);
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public void initView() {

    }

    @Override
    public void addViewListener() {
        videoView.setOnPlayStateChangeListener(new SimpleVideoView.OnPlayStateChangeListener() {
            @Override
            public void onChange(PlayInfo info) {
                NmcUtils.sendToNmcPlayerStatusChanged(info.getFileId(),
                        PlayStateChangeBean.STATUS_PLAY, 0);
                if(!visiable){
                    LogUtil.v(TAG, " setOnPlayStateChangeListener onChange onVideoPause");
                    videoView.getCurrentPlayer().onVideoPause();
                }
            }

            @Override
            public void onPlay(PlayInfo info, int progress) {
                //回复 nmc 播放状态变化
                if (info == null) {
                    onEmpty();
                    LogUtil.v(TAG,"onPlay onEmpty 已经执行");
                    return;
                }
                NmcUtils.sendToNmcPlayerStatusChanged(info.getFileId(),
                        PlayStateChangeBean.STATUS_PLAY, progress);
            }

            @Override
            public void onPause(PlayInfo info, int progress) {
                if (info == null) {
                    LogUtil.v(TAG,"onPause onEmpty 已经执行");
                    onEmpty();
                    return;
                }
                NmcUtils.sendToNmcPlayerStatusChanged(info.getFileId(),
                        PlayStateChangeBean.STATUS_PAUSE, progress);
            }

            @Override
            public void onEmpty() {

                Message msg = mHandler.obtainMessage();
                msg.what = HANDLER_WHAT_SAVE_PROGRESS;
                msg.obj = -1;
                msg.arg1 = 0;
                msg.sendToTarget();
                mPlayList.clear();
                NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
            }
        });


    }



    /**
     * 设置播放列表，并播放
     *
     * @param playInfoList 播放列表
     */
    public void setUp(List<PlayInfo> playInfoList) {
        if (videoView == null) {
            return;
        }
        mPlayList.clear();
        mPlayList.addAll(playInfoList);
        videoView.setUp(playInfoList, false, 0, null);

    }

    public void play() {
        if (videoView == null) {
            return;
        }
        mMainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LogUtil.v(TAG, " play startPlayLogic ");
                videoView.startPlayLogic();
            }
        }, 1000);
    }

    /**
     * 追加列表
     *
     * @param playInfoList
     */
    public void appendPlayList(List<PlayInfo> playInfoList) {
        if (videoView == null) {
            return;
        }
        mPlayList.addAll(playInfoList);
        videoView.addList(playInfoList);
    }

    /**
     * 改变播放状态
     *
     * @param state 要改变的状态
     */
    public void changePlayState(PlayStateChangeBean state) {

        LogUtil.v(TAG, " changePlayState ");

        PlayInfo currentPlayInfo = videoView.getCurrentPlayInfo();
        if (currentPlayInfo == null) {
            return;
        }
        int fileId = state.getFileId();
        if (fileId == currentPlayInfo.getFileId()) {
            if (state.getStatus() == PlayStateChangeBean.STATUS_PLAY) {
                isAutoPlay = true;
                int states=videoView.getCurrentState();
                LogUtil.v(TAG,"states= "+states);
                if (videoView.getCurrentState() == SimpleVideoView.CURRENT_STATE_NORMAL) {
                    videoView.startPlayLogic();
                    LogUtil.v(TAG, " changePlayState startPlayLogic ");
                } else {
                    if(GSYVideoView.CURRENT_STATE_PAUSE==states){
                        videoView.getClickStart();
                    }else if(GSYVideoView.CURRENT_STATE_PLAYING==states){
                        videoView.seekTo((long) ((state.getProgress() * 1.0f / 100) * currentPlayInfo.getDuration()));
                        LogUtil.v(TAG, " changePlayState onVideoResume ");
                        videoView.onVideoResume();
                    }else {
                        videoView.seekTo((long) ((state.getProgress() * 1.0f / 100) * currentPlayInfo.getDuration()));
                        LogUtil.v(TAG, " else changePlayState onVideoResume ");
                        videoView.onVideoResume();
                    }
                }
            } else {
//                isAutoPlay = false;
//                LogUtil.v(TAG, " changePlayState onVideoPause ");
//                videoView.onVideoPause();

                videoView.getClickStart();
//                LogUtil.v(TAG,"getClickStart");
            }
        } else {
            List<PlayInfo> list = videoView.getPlayList();
            for (PlayInfo playInfo : list) {
                if (playInfo.getFileId() == fileId) {
                    videoView.setUp(playInfo, false, null);
                    videoView.seekTo((long) ((state.getProgress() * 1.0f / 100) * playInfo.getDuration()));
                    isAutoPlay = true;
                    mMainHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            videoView.startPlayLogic();
                        }
                    }, 1000);
                    break;
                }
            }
        }
    }

    /**
     * 删除指定播放列表
     *
     * @param removeFileId 当前删除的播放记录，>-1 为删除单条，=-1为清空操作
     */
    public void removePlayInfo(int removeFileId) {
        if (removeFileId > -1) {
            //删除单条
            int position = -1;
            for (int i = 0; i < mPlayList.size(); i++) {
                PlayInfo info = mPlayList.get(i);
                if (info.getFileId().equals(removeFileId)) {
                    position = i;
                    break;
                }
            }
            if (position > -1) {
                mPlayList.remove(position);
                videoView.removePlayInfo(position);
            }
        } else {
            //清空
            videoView.removeAllPlayList();
        }
    }

    public void setPlayMode(int mode) {
        videoView.setLoopMode(mode);
    }

    public List<PlayInfo> getPlayInfoList() {
        return videoView.getPlayList();
    }




    @Override
    public void onLeftPress() {
        super.onLeftPress();
        if (videoView == null) {
            return;
        }
        LogUtil.v(TAG, " onLeftPress previous ");
        videoView.previous();
    }

    @Override
    public void onRightPress() {
        super.onRightPress();
        if (videoView == null) {
            return;
        }
        LogUtil.v(TAG, " onLeftPress next ");
        videoView.next();
    }

    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onPlayModeChange(PlayModeChangedEvent event) {
        if (event.getMode() == PlayInfo.TYPE_VIDEO) {
            if (!isInit) {
                mHandler.sendEmptyMessage(HANDLER_WHAT_QUERY_PLAY_LIST);
                isInit = true;

                return;
            }
            NmcUtils.sendToNmcPlayListChanged(PlayInfo.TYPE_VIDEO, mPlayList);
            if (isAutoPlay) {
                if (mPlayList.isEmpty()) {
                    NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
                }
            } else {
                if (mPlayList.isEmpty()) {
                    NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
                    return;
                }
                PlayInfo curPlay = videoView.getCurrentPlayInfo();
                if (curPlay != null) {
                    int percent = (int) (videoView.getCurrentTime() * 1.0f / curPlay.getDuration() / 1000 * 100);
                    NmcUtils.sendToNmcPlayerStatusChanged(curPlay.getFileId(), PlayStateChangeBean.STATUS_PAUSE, percent);
                }
            }
        }
    }

    private boolean visiable = true;

    @Override
    public void onVisible() {
        super.onVisible();
        visiable = true;
        LogUtil.v(TAG, " onVisible");
        SPManager.getInstance().saveCurrentPlayerMode(PlayInfo.TYPE_VIDEO);
        LogUtil.v(TAG, "isInit= "+isInit+" "+"isAutoPlay= "+isAutoPlay);
        if (isInit && isAutoPlay) {
            if (!mPlayList.isEmpty()) {
                int currentPositionWhenPlaying = videoView.getCurrentPlayer().getCurrentPositionWhenPlaying();

                if (currentPositionWhenPlaying > 0) {
                    videoView.getCurrentPlayer().onVideoResume();
                    LogUtil.v(TAG, " onVisible getCurrentPlayer onVisible onVideoResume : " + videoView.getCurrentState() + " currentPositionWhenPlaying : " + currentPositionWhenPlaying);
                } else {
                    videoView.getCurrentPlayer().startPlayLogic();

                }

            }
        }

        videoView.setGSYVideoProgressListener(new GSYVideoProgressListener() {
            @Override
            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                PlayInfo info = videoView.getCurrentPlayInfo();
                if (info == null) {
                    LogUtil.v(TAG,"播放信息为空");
                    return;
                }
                int currentPositionSec = currentPosition / 1000;
                int durationSec = duration / 1000;
                int computeProgress = (int) ((currentPositionSec * 1.0f / durationSec) * 100);
                if (computeProgress == 0) {
                    return;
                }
                if (computeProgress != curProgress) {
                    Logger.d("progress ====> " + computeProgress + "     isPlaying?==>" + (videoView.getCurrentState() == CURRENT_STATE_PLAYING));
                    curProgress = computeProgress;
                    Message msg = mHandler.obtainMessage();
                    msg.what = HANDLER_WHAT_SAVE_PROGRESS;
                    msg.obj = info.getId();
                    msg.arg1 = curProgress;
                    msg.sendToTarget();

                    NmcUtils.sendToNmcPlayerStatusChanged(info.getFileId(),
                            videoView.getCurrentState() == CURRENT_STATE_PLAYING ?
                                    PlayStateChangeBean.STATUS_PLAY : PlayStateChangeBean.STATUS_PAUSE,
                            progress);
                }
            }
        });
    }


//    @Override
//    public void onStart() {
//        super.onStart();
//
//        LogUtil.v(TAG, " onStart");
//
//        if (SPManager.getInstance().getCurrentPlayerMode() != PlayInfo.TYPE_VIDEO) {
//            return;
//        }
//        if (videoView != null && isAutoPlay) {
//
//            LogUtil.v(TAG, " onVisible getCurrentPlayer onStart onVideoResume ");
//            videoView.getCurrentPlayer().onVideoResume();
//
//        }
//    }
//
//    @Override
//    public void onStop() {
//        super.onStop();
//
//        LogUtil.v(TAG, " onStop");
//
//        if (videoView != null) {
//            LogUtil.v(TAG, " onVisible getCurrentPlayer onStop onVideoResume");
//            videoView.getCurrentPlayer().onVideoPause();
//        }
//    }

    @Override
    public void onInVisible() {
        super.onInVisible();
        visiable = false;
        LogUtil.v(TAG, " onInVisible");

        if (videoView != null) {

            int currentPositionWhenPlaying = videoView.getCurrentPlayer().getCurrentPositionWhenPlaying();
            videoView.getCurrentPlayer().onVideoPause();
            LogUtil.v(TAG, " onVisible getCurrentPlayer onInVisible onVideoPause" + videoView.getCurrentState() + " currentPositionWhenPlaying " + currentPositionWhenPlaying);
            SPUtils.getInstance().put("getindex",2);
            videoView.setGSYVideoProgressListener(null);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.v(TAG,"onDestroyView");
        EventBus.getDefault().unregister(this);
        mHandlerThread.quit();
        mHandler.removeCallbacksAndMessages(null);
        mMainHandler.removeCallbacksAndMessages(null);
        mMainHandler = null;
        mHandlerThread = null;
        mHandler = null;
    }
}
